<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Sys\Permission;

class PermissionController extends Controller
{

    //获取所有的权限-树状结构
    public function listTree(Request $request)
    {
        $data = $request->all();
        try {
            $type = $data['tree'] ?? true;
            $Permission = new Permission();
            $data = $Permission->getAllPermission($type);
            return success($data);
        } catch (Exception $e) {
            return error(null, $e->getMessage());
        }
    }

    //获取所有的权限
    public function list(Request $request)
    {
        $param = $request->all();
        try {
            $Permission = new Permission();
            $data = $Permission->getAllMenu($param);
            return success($data);
        } catch (Exception $e) {
            return error(null, $e->getMessage());
        }
    }



    public function add(Request $request)
    {
        try {
            $data = $request->all();
            $validator = Validator::make(
                $data,
                [
                    'code' => 'required|unique:sys_menu,code',
                    'name' => 'required',
                    'type' => 'required|in:' . '0,1'

                ],
                [
                    'code.required' => '编码不能为空',
                    'type.required' => '类型不能为空',
                    'type.in' => '类型值不在范围',
                    'code.unique' => '编码必须唯一',
                    'name.required' => '名称不能为空',
                ]
            );
            if ($validator->fails()) {
                throw new Exception($validator->errors()->first());
            }
            $res = Permission::create($data);
            if (!$res) {
                throw new Exception('添加失败');
            }
            return success();
        } catch (Exception $e) {
            return error(null, $e->getMessage());
        }
    }

    public function delete(Request $request)
    {
        try {
            $data = $request->all();
            $validator = Validator::make(
                $data,
                [
                    'id' => 'required|exists:sys_menu,id',
                ],
                [
                    'id.required' => 'id不能为空',
                    'id.exists' => '删除的权限不存在',
                ]
            );
            if ($validator->fails()) {
                throw new Exception($validator->errors()->first());
            }
            $Permission = new Permission();
            $data = $Permission->where('id', '=', $request->id)->delete();
            return success($data);
        } catch (Exception $e) {
            return error(null, $e->getMessage());
        }
    }


    //获取所有一级权限
    public function getFirst()
    {
        $data = (new Permission())->getFirst();
        return success($data);
    }
}
